package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Message;
import cn.wolfcode.trip.base.mapper.MessageMapper;
import cn.wolfcode.trip.base.query.LetterQuery;
import cn.wolfcode.trip.base.service.ILetterService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class LetterServiceImpl implements ILetterService {
    @Autowired
    private MessageMapper messageMapper;
    @Override
    public PageInfo queryForPage(LetterQuery qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<Message> letters = messageMapper.selectMyRecivedLetters(qo);
        return new PageInfo(letters);
    }

    @Override
    public void updateLetterState(int isnew,Long userId) {
        messageMapper.updateLetterState(isnew,userId);
    }

    @Override
    public void sendLetters(Message letter, Long reciverId) {
        letter.setUser(UserContext.getCurrentUser());
        letter.setCreateTime(new Date());
        //初始化状态为 新  状态
        letter.setIsnew(1);
        messageMapper.insert(letter);
        //维护关联关系表
        messageMapper.insertRelation(reciverId,letter.getId());

    }

    @Override
    public PageInfo querySentLettersForPage(LetterQuery qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<Message> messages=messageMapper.selectSentLettersForPage(qo);
        return new PageInfo(messages);
    }

    /**
     * 批量删除私信(实际上只是更新状态；不左物理删除)
     * @param ids
     * @param type 删除类别（DELETE_MY_RECIVE:代表删除我接收到的私信；DELETE_MY_SENT代表删除我发送的私信）
     * @return
     */
    @Override
    public void batshDelete(Long[] ids,String type) {

            if("DELETE_MY_RECIVE".equals(type)){//用户删除自己所接收到的私信
                for (Long id : ids) {
                    //批量更新作者私信valid字段
                    messageMapper.updateRecivedLettersValidById(id);
                }
            }
            if("DELETE_MY_SENT".equals(type)){
                for (Long id : ids) {
                    //批量更新接收者私信valid字段
                    messageMapper.updateMyLettersValidById(id);
                }
            }

    }

    /**
     * 清空私信
     * @param userId
     * @param type DELETE_MY_RECIVE:代表清空我接收到的私信；DELETE_MY_SENT代表清空我发送的私信
     */
    @Override
    public void clearLetters(Long userId, String type) {
        if("DELETE_MY_RECIVE".equals(type)){//清空当前用户接收到的私信
            messageMapper.updateRecivedLetterValidByUserId(userId);
        }
        if("DELETE_MY_SENT".equals(type)){//清空掉我发送的私信信息
            messageMapper.updateMyLetterValidByUserId(userId);
        }
    }
}
